Range Sum Query - Mutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.

Example:

  1. Given nums = [1, 3, 5]
  2. sumRange(0, 2) -> 9
  3. update(1, 2)
  4. sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

Solution:

  1. public class NumArray {
  2. int[] arr; // stores nums[]
  3. int[] BITree; // binary indexed tree
  4. public NumArray(int[] nums) {
  5. int n = nums.length;
  6. arr = new int[n];
  7. BITree = new int[n + 1];
  8. for (int i = 0; i < n; i++) {
  9. update(i, nums[i]); // init BITree[]
  10. arr[i] = nums[i]; // init arr[]
  11. }
  12. }
  13. void update(int i, int val) {
  14. int diff = val - arr[i]; // get the diff
  15. arr[i] = val; // update arr[]
  16. i++;
  17. while (i <= arr.length) {
  18. BITree[i] += diff; // update BITree[]
  19. i += i & (-i); // update index to that of parent
  20. }
  21. }
  22. int getSum(int i) {
  23. int sum = 0;
  24. i++;
  25. while (i > 0) {
  26. sum += BITree[i]; // accumulate the sum
  27. i -= i & (-i); // move index to parent node
  28. }
  29. return sum;
  30. }
  31. public int sumRange(int i, int j) {
  32. return getSum(j) - getSum(i - 1);
  33. }
  34. }
  35. // Your NumArray object will be instantiated and called as such:
  36. // NumArray numArray = new NumArray(nums);
  37. // numArray.sumRange(0, 1);
  38. // numArray.update(1, 10);
  39. // numArray.sumRange(1, 2);